import os
import json
import logging
import requests
import time
import hmac
import hashlib
import base64
import urllib.parse
from urllib.parse import urlparse
from flask import Flask
from flask import request
#==========钉钉部分
#获取时间戳，签名值
def getSignTimestamp(signature):
    timestamp = str(round(time.time() * 1000))
    secret = signature
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return (timestamp,sign)

#发送text信息到钉钉
def sendDing(url,content):
    headers = {
        'Content-Type': 'application/json',
    }
    data = {
            "msgtype": "text",
            "text": {
                "content": content
            }
        }
    r = requests.post(url,headers=headers,data=json.dumps(data)).text
    json_r = json.loads(r)

    if json_r['errcode'] == 0:
        print("发送成功")
    else:
        print("发送失败")

def run_send(text):
    token = os.getenv('ding_token')
    secret = os.getenv('ding_secret')

    if not token:
        app.logger.error('你没有提供dingding的token值')
        return
    if not secret:
        app.logger.error('你没有提供dingding的secret值')
        return
    (times,signs) = getSignTimestamp(secret)
    webhook = 'https://oapi.dingtalk.com/robot/send?access_token=' + token
    urls = webhook + '&timestamp=' + times + '&sign=' + signs
    sendDing(url=urls,content=text)

#==========web配置部分
app = Flask(__name__)

logging.basicConfig(
    level=logging.DEBUG if os.getenv('LOG_LEVEL') == 'debug' else logging.INFO,
    format='%(asctime)s %(levelname)s %(message)s')


@app.route('/', methods=['POST', 'GET'])
def send():
    if request.method == 'POST':
        post_data = request.get_data()
        app.logger.debug(post_data)
        send_alert(json.loads(post_data))
        return 'success'
    else:
        return 'weclome to use prometheus alertmanager dingtalk webhook server!'

#==========警报处理并发送
def send_alert(data):
    print('alertmanager数据内容：%s'%data)
    for i in data['alerts']:
        try:
            alerts_type = data['status']
            alerts_status = data['commonLabels']['severity']
            alerts_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            alerts_host = i['labels']['instance']
            alerts_alias_name = i['labels']['alias_name']
            alerts_name = i['labels']['alertname']
            alerts_value = round(float(i['annotations']['value']),2)
            alerts_text = i['annotations']['description']
            alerts_summary = i['annotations']['summary']
        except KeyError as e:
            conten = "报警标签无法获取：%s"%str(e)
            run_send(conten)
            continue
        if alerts_type == 'resolved': #恢复
            conten = '告警恢复\n告警名称：%s\n主机别名：%s\n告警状态：%s\n告警主机：%s\n告警阈值：%s\n告警条件：%s\n告警内容：%s\n告警时间：%s'%(alerts_name,alerts_alias_name,alerts_status,alerts_host,alerts_value,alerts_text,alerts_summary,alerts_time)
        else:
            conten = '【异常】告警\n告警名称：%s\n主机别名：%s\n告警状态：%s\n告警主机：%s\n告警阈值：%s\n告警条件：%s\n告警内容：%s\n告警时间：%s'%(alerts_name,alerts_alias_name,alerts_status,alerts_host,alerts_value,alerts_text,alerts_summary,alerts_time)
        run_send(conten)  
        time.sleep(3) 


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)